import { JXDef } from "../../../conventions/JXCommon";
import { PRIORITY_VIEW } from "../../../Core/CoreDefine";
import { GCtrl } from "../../../Core/GCtrl";
import GChild from "../../../Core/GView/GChild";
import { BUFFINFO, CMsg, ITEM_TYPE } from "../../Common/Define";
import { LCoin } from "../../Common/Language";
import { VIEW_ID } from "../../Common/UI";
import { Res } from "../../Common/UIResources";
import GameMgr from "../../Logic/GameMgr";
import { CURRENCY } from './../../Common/Define';
import HangPage from "./HangPage";
const { ccclass, property, menu, executeInEditMode } = cc._decorator;
@ccclass @menu('View/Common/TopUiItem')

export default class TopUiItem extends GChild {

    @property({type: cc.Label,tooltip: "宝石数量"})  lb_gem: cc.Label = null;

    @property({type: cc.Label,tooltip: "金币数量"})  lb_coin: cc.Label = null;

    @property({type: cc.Node,tooltip: "返回按钮"})  exitBtn: cc.Node = null;

    @property({type: cc.Node,tooltip: "设置按钮"})  setting: cc.Node = null;

    @property({type: cc.Node,tooltip: "金币"})  coin: cc.Node = null;

    @property({type: cc.Node,tooltip: "玉石"})  gem: cc.Node = null;

    @property({type: cc.Node,tooltip: "粮草"})  armyBg: cc.Node = null;

    @property({type: cc.Label,tooltip: "粮草数量"})  lb_army: cc.Label = null;

    @property({type: cc.Node,tooltip: "粮草底"}) armyBgS: cc.Node = null;

    @property({type: cc.Node,tooltip: "粮草底"}) armyAdd: cc.Node = null;

    @property({type: cc.Node,tooltip: "头像Node"})  avatarNode: cc.Node = null;

    @property({type: cc.Node,tooltip: "标题Node"})  bgNode: cc.Node = null;

    @property({type: cc.Label,tooltip: "标题Node"})  tilLab: cc.Label = null;

    /**是否抽卡招募中 */
    private _isRecruit: boolean = true;
    //点击设置
    protected onSetClick() {

        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.setting);
    }

    protected onAvatarClick() {

        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.userInfoView);
    }

    protected _winId: number = null;

    /**0头像普通模式， 1隐藏头像 */
    public mode:number = 0;

    onGLoad() {
        if (cc.sys.os == cc.sys.OS_ANDROID) {
            this.gem.setPosition(-124, 20);
            this.armyBg.setPosition(59, 20);
        }

        if (cc.sys.os == cc.sys.OS_IOS) {
            this.gem.setPosition(50, -21);
            this.armyBg.setPosition(-124, 20);
            this.armyBgS.scaleX = 3.1;
            this.armyAdd.x = 400;
            this.lb_army.node.x = 340;
        }

        this.bgNode.active = false;
        this.avatarNode.active = true;


        this.init();
        GCtrl.ES.on(CMsg.client.bag.onCurrencyChange, this, this.init.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.view.onViewChange, this, this.onViewChange.bind(this), PRIORITY_VIEW);
    }

    public setModeType(mode:number = 0, title:string = ""){
        this.mode = mode;
        this.bgNode.active = this.mode == 1;
        this.avatarNode.active = this.mode == 0;

        this.tilLab.string = title
    }


    /**返回主页 */
    public return() {
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.mainPage);
    }

    public onViewChange() {
        let hangPage = this.getComponent(HangPage);
        if (!hangPage) {
            return;
        }
        let curView = hangPage.getCurWin();
        // console.log("当前窗口id", curView);
        if ((curView == VIEW_ID.storePage) || (curView == VIEW_ID.heroPage) || (curView == VIEW_ID.chuangguanView) || (curView == VIEW_ID.bagView)) {
            this.setting.active = false;
            this.exitBtn.active = false;

            if (curView == VIEW_ID.heroPage){
                this.setModeType(1, "武将")
            }
            else if (curView == VIEW_ID.bagView){
                this.setModeType(1, "背包")
            }
            else if (curView == VIEW_ID.chuangguanView){
                this.setModeType(1, "闯关")
            }
            
        }

        if (curView == VIEW_ID.home) {
            this.setting.active = true;
            this.exitBtn.active = false;

            this.setModeType(0);
        }
    }

    public addCoin() {
        if (!this._isRecruit) {
            return
        }
        let cost = [CURRENCY.GOLD, ITEM_TYPE.CURRENCY, 1];
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.currencyFrame, cost, 1);

    }

    public addYuSi() {
        if (!this._isRecruit) {
            return
        }
        let cost = [CURRENCY.YUSHI, ITEM_TYPE.CURRENCY, 1];
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.currencyFrame, cost, 1);
    }

    public addArmy() {
        if (!this._isRecruit) {
            return
        }
        // let cost = [CURRENCY.WHEAT, ITEM_TYPE.CURRENCY, GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.forageUp)];
        // GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.currencyFrame, cost, 1);

        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.comonTipView, 3);
    }

    public init() {
        this.lb_coin.string = LCoin(GameMgr.RBagData.getMegreItems(CURRENCY.GOLD, ITEM_TYPE.CURRENCY).num) + '';
        this.lb_gem.string = LCoin(GameMgr.RBagData.getMegreItems(CURRENCY.YUSHI, ITEM_TYPE.CURRENCY).num) + ''; + '';
        let wheat: number = GameMgr.systemConfig.value(JXDef.SYS_CONFIG_KEY.basicsWheat);
        wheat += GameMgr.lUserData.getUserBuff(BUFFINFO.InitBattlefieldRes);
        // console.log("12312");


        this.lb_army.string = wheat + GameMgr.RBagData.getMegreItems(CURRENCY.WHEAT, ITEM_TYPE.CURRENCY).num + '';
    }

    protected change(CURRENCYANIM: CURRENCYANIM) {
        var coin = null;
        var worldPos = null;
        var ccPos = null;
        if (CURRENCYANIM.id == CURRENCY.GOLD) {
            coin = GameMgr.uiMgr.uiRoot.getChildByName('TopUiItem').getChildByName('coinBg').getChildByName('coin');
            // worldPos = coin.parent.convertToWorldSpaceAR(coin.position);
            // ccPos = this.node.convertToNodeSpaceAR(worldPos);
        }
        if (CURRENCYANIM.id == CURRENCY.YUSHI) {
            coin = GameMgr.uiMgr.uiRoot.getChildByName('TopUiItem').getChildByName('gemBg').getChildByName('gem');
            // worldPos = coin.parent.convertToWorldSpaceAR(coin.position);
            // ccPos = this.node.convertToNodeSpaceAR(worldPos);
        }

        this.playAnimation(new cc.Vec2(0, 0), ccPos, () => {

        }, CURRENCYANIM);
    }

    /**
* 已知两点求距离
* @param {cc.Vec2} pos1
* @param {cc.Vec2} pos2
*/
    public calcDistance(pos1: cc.Vec2, pos2: cc.Vec2) {
        let xdiff = pos1.x - pos2.x;
        let ydiff = pos1.y - pos2.y;
        let dis = Math.pow((xdiff * xdiff + ydiff * ydiff), 0.5);
        return dis;
    };

    /**
     * 播放金币落袋特效
     * @param startPos  生成位置
     * @param _endPoint 
     * @param callback 完成后的回调
     */
    public playAnimation(startPos: cc.Vec2, _endPoint: cc.Vec2, callback: Function, CURRENCYANIM: CURRENCYANIM) {
        let ranCount = 15
        //最终位置
        let endPos = _endPoint;
        this.playCoinFlyAnim(ranCount, startPos, endPos, callback, CURRENCYANIM)
    }

    /**金币落袋具体实现方法 */
    protected playCoinFlyAnim(count: number, startPos: cc.Vec2, endPos: cc.Vec2, callback: Function, CURRENCYANIM: CURRENCYANIM, r: number = 50) {
        //金币分散成圆
        let points = this.getCirclePoints(r, startPos, count);
        let coinNodeList = points.map(pos => {
            var coin = new cc.Node("New Sprite");
            coin.addComponent(cc.Sprite);
            var sprite = coin.getComponent(cc.Sprite);
            if (CURRENCYANIM.id == CURRENCY.GOLD) {
                this.assetImpl.spriteAtlasFrame(sprite, Res.texture.views.icon, 'icon_101');
            }
            if (CURRENCYANIM.id == CURRENCY.YUSHI) {
                this.assetImpl.spriteAtlasFrame(sprite, Res.texture.views.icon, 'icon_100');
            }
            // cc.find('Canvas').addChild(coin);
            this.node.addChild(coin);
            coin.setPosition(startPos.x, startPos.y);
            return {
                node: coin,
                startPos: startPos,
                midPos: pos,
                endPos: endPos,
                dis: this.calcDistance(pos, endPos)
            }
        })

        //执行动作
        let i = 0;
        coinNodeList.forEach((item, idx) => {
            i++;
            cc.tween(item.node)
                .to(0.5, { position: cc.v2(item.midPos.x, item.midPos.y) })//初始位置
                .delay(idx * 0.01)
                .to(1, { position: cc.v2(item.endPos.x, item.endPos.y) })//终点
                .call(() => {
                    item.node.destroy();
                })
                .union()
                .start()
        });
        this.scheduleOnce(() => {
            callback();
        }, 1.5)
    }
    /**
    * 以某点为圆心，生成圆周上等分点的坐标
    *
    * @param {number} r 半径
    * @param {cc.Vec2} pos 圆心坐标
    * @param {number} count 等分点数量
    * @param {number} [randomScope=80] 等分点的随机波动范围
    * @returns {cc.Vec2[]} 返回等分点坐标
    */
    protected getCirclePoints(r: number, pos: cc.Vec2, count: number, randomScope: number = 50): cc.Vec2[] {
        let points = []
        for (let i = 0; i < count; i++) {
            let radians = (Math.PI / 180) * Math.round(360 / count)
            let x = pos.x + r * Math.sin(radians * i)
            let y = pos.y + r * Math.cos(radians * i)
            points.unshift(cc.v3(x + Math.random() * randomScope, y + Math.random() * randomScope, 0))
        }
        return points
    }
}   